package airportCoordinationMonitor;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class OutputRedirector implements Runnable{
	private SharedProcess active;
	private SharedProcess pasive;
	
	public OutputRedirector(SharedProcess activeProc, SharedProcess pasiveProc)
	{
		active = activeProc;
		pasive = pasiveProc;
	}
	
	public void run()
	{
		InputStream actInputStream = null, pasInputStream = null;
		BufferedReader actReader = null, pasReader = null;
		String buffer;
		
		while(true)
		{
			if (active.flag())
			{
				actInputStream = active.process().getInputStream();
				actReader = new BufferedReader(new InputStreamReader(actInputStream));
				active.reset_flag();
			}
			if (pasive.flag())
			{
				pasInputStream = pasive.process().getInputStream();
				pasReader = new BufferedReader(new InputStreamReader(pasInputStream));
				pasive.reset_flag();
			}
			
			try{
				buffer = null;
				int chars = actInputStream.available();
				if (chars>0)
				{
					char[] input = new char[chars];
					actReader.read(input, 0, chars);
					buffer = String.valueOf(input);
					String[] lines = buffer.split("\n");
					for (int i = 0; i < lines.length; i++)
						if (!lines[i].equals(""))
							System.out.print("ACTIVE: " + lines[i] + "\n");
				}
			}catch(Exception e){ System.out.print("Error getting active coordination messages, skipping: " + e.getMessage() + "\n"); buffer = null; }
			
			try{
				buffer = null;
				int chars = pasInputStream.available();
				if (chars>0)
				{
					char[] input = new char[chars];
					pasReader.read(input, 0, chars);
					buffer = String.valueOf(input);
					String[] lines = buffer.split("\n");
					for (int i = 0; i < lines.length; i++)
						if (!lines[i].equals(""))
							System.out.print("PASIVE: " + lines[i] + "\n");
				}
			}catch(Exception e){ System.out.print("Error getting pasive coordination messages, skipping: " + e.getMessage() + "\n"); buffer = null; }
			
			try{
				Thread.sleep(100);
			}catch(Exception e){ System.out.print("Warning OutputRedirector can't sleep.\n"); }
		}
	}
}
